<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Auth;
use Illuminate\Database\Eloquent\Relations\HasOne;

/**
 * 站点
 * @package App\Models
 */
class Site extends Model
{
    use HasFactory;

    //哪些字段可以批量填充到表
    protected $fillable = ['title', 'domain', 'module_id', 'config', 'template_id', 'avatar', 'qq', 'github', 'home', 'weibo', 'wechat', 'name', 'keyword', 'description', 'logo', 'icp', 'tel', 'email', 'counter'];

    //字段类型转换
    protected $casts = [
        'config' => 'array'
    ];

    protected $hidden = [
        'config'
    ];
    protected $appends = ['permission'];

    /**
     * 验证规则
     *
     * @return void
     */
    public function getPermissionAttribute()
    {
        return [
            'edit' => Auth::check() && Auth::user()->can('update', $this),
        ];
    }

    /**
     * 站长
     * @return void
     */
    public function master()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * 站点默认模块
     * @return HasOne
     */
    public function module()
    {
        return $this->belongsTo(Module::class, 'module_id');
    }

    //关联公众号
    public function wechats()
    {
        return $this->hasMany(WeChat::class);
    }

    /**
     * 站长
     * @param Site $site
     * @param User $user
     */
    public function isMaster(User $user)
    {
        return $user->id == 1 || $this->master->id == $user->id;
    }
}
